//配置路由的地方
import Vue from 'vue';
import VueRouter from 'vue-router';
import routes from './routes';
import store from "@/store";
//使用插件
Vue.use(VueRouter);

//先把VueRouter原型对象的push、replace保存一份
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;

//重写push|replace(原先的有bug？)
//第一个参数告诉原来push方法往哪里跳转
//第二个参数为成功的回调
//第三个参数为失败的回调
VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        originPush.call(this, location, resole, reject);
    } else {
        originPush.call(this, location, () => { }, () => { })
    }
}
VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve && reject) {
        originReplace.call(this, location, resole, reject);
    } else {
        originReplace.call(this, location, () => { }, () => { })
    }
}
//配置路由
let router = new VueRouter({
    //配置路由,在routes.js里配置然后引入
    routes,
    //滚动行为,设置每次路由跳转后的滚动条
    scrollBehavior(to, from, savedPosition) {
        // 始终滚动到顶部
        return { y: 0 }
    },
})

//全局守卫，前置守卫
 router.beforeEach(async (to, from, next) => {
    let token = store.state.user.token;               //获取令牌
    let id = store.state.user.userInfo.id;        //获取用户信息

    if (token) {    //用户已经登录
        if (to.path == '/login' || to.path == '/register') {    //跳转的是注册||登陆页面不给跳，返回首页
            next('/');
        } else {
            if (id) { //登录且有用户信息给正常跳转
                next();
            } else {
                //登录了且没有用户信息
                //在路由跳转之前获取用户信息且放行
                try {
                    await store.dispatch('getUserInfo');    //获取用户信息
                    next();
                } catch (error) {
                    //token失效重新登录
                    await store.dispatch('userlogout');     //退出登录
                    next('/login')
                    next()
                }
            } next();
        }
    } else {
        //未登录：不能去交易相关、支付相关页面【pay|paysuccess】、不能去个人中心
        let toPath = to.path;
        if (to.meta.needUserInfo) {//跳转的页面是不是pay、个人中心等游客不能去的页面，是则跳转到登录页
            //未登录时跳转到用户专用页面时存储该页面于地址栏中，为了登陆后不跳转到首页而是直接跳到目标页
            next('/login?redirect='+toPath)         
        } else {
            next();
        }
    }
});


export default router;
